<template>
  <div class="components-score-prod-transport mod-prod-prod-transport">
    <!-- 运费模板 -->
    <el-form-item

      :label="$t('freight.shippinngs')"
    >
      <el-radio
        v-model="_dataForm.tableRate"
        :label="0"
      >
        {{ $t('freight.freeShipping') }}
      </el-radio>
      <el-radio
        v-model="_dataForm.tableRate"
        :label="-1"
        @change="onTableRateChanne"
      >
        {{ $t('freight.fixedFreight') }}
      </el-radio>
      <el-radio
        v-model="_dataForm.tableRate"
        :label="1"
      >
        {{ $t('freight.freTempl') }}
      </el-radio>
    </el-form-item>
    <el-form-item
      v-show="_dataForm.tableRate===1"
      :label="$t('freight.freTempl')"
      :rules="[{ required: true, message: $t('freight.shippingtBeEmpty')}]"
    >
      <el-select
        v-model="transportId"
        :placeholder="$t('tip.select')"
        @change="onChangeTransport"
      >
        <el-option
          v-for="transport in transportList"
          :key="transport.transportId"
          :label="transport.transName"
          :value="transport.transportId"
        />
      </el-select>
      <!--      新建/刷新-->
      <div
        class="default-btn text-btn"
        @click="onRefreshChange"
      >
        {{ $t('transport.refresh') }}
      </div>
      <el-divider direction="vertical" />
      <div
        class="default-btn text-btn"
        @click.stop="onAddOrUpdate()"
      >
        {{ $t('transport.newConstruction') }}
      </div>
    </el-form-item>
    <el-form-item
      v-if="_dataForm.tableRate===-1"
      :label-width="$t('language')=='English'?'180px':''"
      :label="$t('freight.fixedFreight')"
      prop="deliveryAmount"
      :rules="[{ required: true, message: $t('transport.pleaseEnterTheAmount'), trigger: 'blur' }]"
    >
      <div class="freight">
        <el-input
          v-model="_dataForm.deliveryAmount"
          type="number"
          :min="0.01"
          maxlength="10"
          :placeholder="$t('transport.pleaseEnterTheAmount')"
          @change="onHandleInputValue(_dataForm.deliveryAmount,'deliveryAmount',0.01,9999)"
        />
      </div>
    </el-form-item>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @close="onAddOrUpdateClose"
      @refresh-data-list="onRefreshChange"
    />
    <el-form-item>
      <el-table
        v-if="transportInfo.transfees"
        :data="transportInfo.transfees"
        style="width: 100%"
        header-cell-class-name="table-header"
        row-class-name="table-row"
      >
        <el-table-column
          :label="$t('transport.distributableArea')"
          width="350"
        >
          <template #default="scope">
            <span v-if="!scope.row.cityList.length">{{ $t('transport.distributableArea') }}</span>
            <span
              v-for="city in scope.row.cityList"
              v-else
              :key="city.areaId"
            >{{ city.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="firstPiece"
          :label="tableTitle[0]"
        />
        <el-table-column
          prop="firstFee"
          :label="tableTitle[1]"
        />
        <el-table-column
          prop="continuousPiece"
          :label="tableTitle[2]"
        />
        <el-table-column
          prop="continuousFee"
          :label="tableTitle[3]"
        />
      </el-table>
    </el-form-item>
    <el-form-item v-if="transportInfo.hasFreeCondition === 1">
      <el-table
        :data="transportInfo.transfeeFrees"
        style="width: 100%"
        header-cell-class-name="table-header"
        row-class-name="table-row"
      >
        <el-table-column
          :label="$t('transport.selArea')"
          width="350"
        >
          <template #default="scope">
            <span
              v-for="city in scope.row.freeCityList"
              :key="city.areaId"
            >{{ city.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="freeType"
          :label="$t('transport.setShopPrice')"
        >
          <template #default="scope">
            <span
              v-if="scope.row.freeType === 0"
            >{{ [$t("transport.fullCount"),$t("transport.fullWeight"),$t("transport.fullVolume")][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 1"
            >{{ $t('transport.fullAmount') + $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 2"
            >{{ [$t("transport.fullCount"),$t("transport.fullWeight"),$t("transport.fullVolume")][transportInfo.chargeType] }}{{ $t("transport.fullAmount1") }}{{ $t("transport.shippingIncluded") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount">
          <template #default="scope">
            <span
              v-if="scope.row.freeType === 1"
            >{{ $t("marketing.full") }}{{ scope.row.amount }}{{ $t("transport.yuan") }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 0"
            >{{ $t("marketing.full") }}{{ scope.row.piece }}{{ [$t("transport.pieces"),'kg','m³'][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
            <span
              v-if="scope.row.freeType === 2"
            >{{ $t("marketing.full") }}{{ scope.row.piece }}{{ $t("transport.yuan") }}{{ $t("product.further") }}{{ $t("marketing.full") }}{{ scope.row.amount }}{{ [$t("transport.pieces"),'kg','m³'][transportInfo.chargeType] }}{{ $t("transport.shippingIncluded") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </div>
</template>

<script setup>
import { areaNameList } from '@/utils/addr'
import AddOrUpdate from '../../transport/components/transport-add-or-update.vue'

const emit = defineEmits(['update:modelValue', 'update:dataForm'])

const props = defineProps({
  modelValue: {
    default: null,
    type: Number
  },
  dataForm: {
    default: () => ({}),
    type: Object
  }
})

const transportId = ref(null)
const addOrUpdateVisible = ref(false)
const transportList = ref([{
  transportId: null,
  transName: ''
}])
const transportInfo = {
  hasFreeCondition: false,
  transfeeFrees: [{ freeCityList: [] }]
}

const tableTitle = computed(() => {
  const titles = [
    [
      $t('transport.firstPiece'),
      $t('transport.transportationCost'),
      $t('transport.continuationPiece'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstWeight'),
      $t('transport.transportationCost'),
      $t('transport.continuedWeight'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstVolume'),
      $t('transport.transportationCost'),
      $t('transport.continuedVolume'),
      $t('transport.continuationCost')
    ]
  ]
  if (transportInfo.value.chargeType) {
    return titles[transportInfo.value.chargeType]
  }
  return titles[0]
})
const _dataForm = computed({
  get () {
    return props.dataForm
  },
  set (val) {
    emit('update:dataForm', val)
  }
})
watch(() => props.modelValue, (val) => {
  transportId.value = val
})
watch(() => _dataForm.value.tableRate, (val) => {
  if (val === 1 && props.modelValue < 1) {
    emit('update:modelValue', null)
  }
})

onMounted(() => {
  getTransportList()
})

const onAddOrUpdateClose = () => {
  addOrUpdateVisible.value = false
}
const onTableRateChanne = () => {
  _dataForm.value.deliveryAmount = 0.01
  _dataForm.value.deliveryAmount = 0.01
}
/**
 * 处理输入框数据
 * @param data
 * @param dataFields
 * @param min 最小值
 * @param max 最大值
 */
const onHandleInputValue = (data, dataFields, min, max) => {
  // eslint-disable-next-line vue/no-mutating-props
  _dataForm.value[dataFields] = checkInput(data)
  if (data || data === 0) {
    // 保留两位小数
    if (data > max) {
      // eslint-disable-next-line vue/no-mutating-props
      _dataForm.value[dataFields] = max
    }
    if (data < min) {
      // eslint-disable-next-line vue/no-mutating-props
      _dataForm.value[dataFields] = min
    }
  }
}

/**
 * 只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = String(num).replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}
const getTransportList = () => {
  http({
    url: http.adornUrl('/platform/transport/list'),
    method: 'get',
    params: http.adornParams({})
  }).then(({ data }) => {
    transportList.value = data
  })
}
// 新增
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
const onRefreshChange = () => {
  getTransportList()
}
const onChangeTransport = (transportId) => {
  emit('update:modelValue', transportId)
  if (transportId !== 0 || transportId !== -1) {
    return
  }
  if (!transportId) {
    return
  }
  http({
    url: http.adornUrl(`/platform/transport/info/${transportId}`),
    method: 'get',
    params: http.adornParams({})
  }).then(({ data }) => {
    transportInfo.value = data
    getAreaListInfo()
  })
}
const getAreaListInfo = () => {
  http({
    url: http.adornUrl('/admin/area/areaListInfo'),
    method: 'get'
  }).then(({ data }) => {
    for (let t = 0; t < transportInfo.value.transfees.length; t++) {
      const areaList = JSON.parse(JSON.stringify(data))
      const addrNameList = areaNameList(areaList, transportInfo.value.transfees[t].cityList)
      transportInfo.value.transfees[t].addrNameList = addrNameList
    }
    for (let f = 0; f < transportInfo.value.transfeeFrees.length; f++) {
      const areaList = JSON.parse(JSON.stringify(data))
      const addrNameList = areaNameList(areaList, transportInfo.value.transfeeFrees[f].freeCityList)
      transportInfo.value.transfeeFrees[f].freeAddrNameList = addrNameList
    }
  })
}
watch(() => transportId.value, (val) => {
  onChangeTransport(val)
})

</script>

<style lang="scss" scoped>
.components-score-prod-transport.mod-prod-prod-transport{
   margin: 50px 0 50px;
   .freight{
    width: 175px;
  }
 }
</style>
